package com.example.study.controller;

import com.alibaba.fastjson.JSON;
import com.example.study.dao.User;
import com.example.study.service.RedisService;
import com.example.study.utils.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "redis")
public class RedisController {

    private static final Logger logger = LoggerFactory.getLogger(RedisController.class);

    @Resource
    private RedisService redisService;

    @GetMapping(value = "string")
    public JsonResult contextLoads() {
        //测试redis的string类型
        redisService.setString("weichat","程序员私房菜");
        logger.info("我的微信公众号为：{}", redisService.getString("weichat"));

        // 如果是个实体，我们可以使用json工具转成json字符串，
        User user = new User("CSDN", "123456");
        redisService.setString("userInfo", JSON.toJSONString(user));
        logger.info("用户信息：{}", redisService.getString("userInfo"));
        String userInfo = redisService.getString("userInfo");
        return new JsonResult<>(userInfo);
    }

    @GetMapping(value = "hash")
    public JsonResult contextHashLoads() {
        //测试redis的hash类型
        User user = new User("CSDN", "123456");
        redisService.setHash("user", "name", JSON.toJSONString(user));
        logger.info("用户姓名：{}", redisService.getHash("user","name"));
        Map map = new HashMap(2);
        map.put("user",redisService.getHash("user","name"));
        return new JsonResult<>(map);
    }

    @GetMapping(value = "list")
    public JsonResult contextListLoads() {
        //测试redis的list类型
        redisService.setList("list", "football");
        redisService.setList("list", "basketball");
        List<String> valList = redisService.getList("list",0,-1);
        for(String value :valList){
            logger.info("list中有：{}", value);
        }
        return new JsonResult<>(valList);
    }
}
